package com.my.collection.stack.v9;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * Created by ZhongGang
 * at 2018/7/26 17:12
 */
public class MySharedLock {
    private final Sync sync;

    public MySharedLock(int permit) {
        this.sync = new Sync(permit);
    }

    public void acquire() {
        this.sync.acquireShared(1);
    }

    public void release() {
        this.sync.releaseShared(1);
    }

    private static class Sync extends AbstractQueuedSynchronizer {
        private int permit;

        Sync(int permit) {
            this.permit = permit;
            setState(this.permit);
        }

        @Override
        protected int tryAcquireShared(int arg) {
            compareAndSetState(getState(), getState() - arg);
            return getState();
        }

        @Override
        protected boolean tryReleaseShared(int arg) {
            return compareAndSetState(getState(), getState() + arg);
        }
    }

}
